# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 19:55:01 2012

@author: Winand
"""

import smtplib
from email.mime.text import MIMEText
from email.Header import Header
import settings as sg
from webapi.log import debug, error
mailcfg={}

def loadMailCfg(smtpconffile, mailconffile):
    try:
        l1=[i.strip() for i in file(mailconffile, 'r').readlines()]
        l2=[i.strip() for i in file(smtpconffile, 'r').readlines()]
    except IOError: error("Failed to load mail conf!")
    cfg=dict([(lambda j: (j[0],j[1].strip("\"")))(i.split("=")) \
                    for i in l1 if i and not i.startswith("#")])
    cfg.update([i.split("=") for i in l2 if i and not i.startswith("#")])
    return cfg

def needConf(f): #DECORATOR
    def func(*args, **kwargs) :
        if mailcfg: return f(*args, **kwargs)
        else: error("Error! No mail conf, cannot send mail")
    return func

@needConf
def send(subj, message):
    server = smtplib.SMTP(mailcfg['host'], mailcfg['port'])
#    server.set_debuglevel(1)
    server.login(mailcfg['username'], mailcfg['password'])
    text = MIMEText(message, 'plain', 'utf-8')
    text['Subject'] = Header(subj, 'utf-8')
    text['From'] = mailcfg['email_returnpath']
    text['To'] = mailcfg['email_recipient_0']
    server.sendmail(text['From'], text['To'], text.as_string())
    server.quit()

#LOAD EMAIL CONFIGURATION
debug("Loading email configuration")
mailcfg=loadMailCfg(sg.SMTP_CFG_FILE, sg.MAIL_CFG_FILE)

if __name__ == '__main__':
    send("Test mail Тест", "Hello there! This is MBL test mail Да это оно")
